package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.PaymentRequestDTO;
import com.example.vendingmachine.dto.PaymentQuery;
import com.example.vendingmachine.dto.PaymentStatsDTO;
import com.example.vendingmachine.entity.PaymentRecord;
import com.example.vendingmachine.service.PaymentService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 支付管理控制器
 */
@RestController
@RequestMapping("/api/payments")
@RequiredArgsConstructor
public class PaymentController {

    private final PaymentService paymentService;

    /**
     * 分页查询支付记录列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('payment:list')")
    public Result<PageInfo<PaymentRecord>> list(PaymentQuery query) {
        return Result.success(paymentService.listPayments(query));
    }

    /**
     * 获取支付记录详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('payment:list')")
    public Result<PaymentRecord> getDetail(@PathVariable Long id) {
        return Result.success(paymentService.getPaymentById(id));
    }

    /**
     * 创建支付记录
     */
    @PostMapping
    @PreAuthorize("hasAuthority('payment:create')")
    public Result<PaymentRecord> create(@Validated @RequestBody PaymentRequestDTO request) {
        return Result.success(paymentService.createPayment(request));
    }

    /**
     * 申请退款
     */
    @PostMapping("/{id}/refund")
    @PreAuthorize("hasAuthority('payment:refund')")
    public Result<Void> refund(@PathVariable Long id) {
        paymentService.refundPayment(id);
        return Result.success();
    }

    /**
     * 获取支付统计数据
     */
    @GetMapping("/stats")
    @PreAuthorize("hasAuthority('payment:list')")
    public Result<PaymentStatsDTO> getStats(PaymentQuery query) {
        return Result.success(paymentService.getPaymentStats(query));
    }

    /**
     * 处理支付回调
     */
    @PostMapping("/callback/{payType}")
    public Result<Void> handleCallback(
            @PathVariable String payType,
            @RequestParam String transactionId,
            @RequestParam String status
    ) {
        paymentService.handlePaymentCallback(payType, transactionId, status);
        return Result.success();
    }

    /**
     * 处理退款回调
     */
    @PostMapping("/refund-callback/{payType}")
    public Result<Void> handleRefundCallback(
            @PathVariable String payType,
            @RequestParam String transactionId,
            @RequestParam String status
    ) {
        paymentService.handleRefundCallback(payType, transactionId, status);
        return Result.success();
    }
} 